package com.example.news.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.news.R;
import com.example.news.bean.UpdateEntity;
import com.example.news.fragment.FindFragment;
import com.example.news.fragment.HomeFragment;
import com.example.news.fragment.LeftMenuFragment;
import com.example.news.fragment.MyFragment;
import com.example.news.utils.UpdateTools;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.umeng.message.PushAgent;
import com.umeng.socialize.UMShareAPI;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends SlidingFragmentActivity {
    private RadioGroup group;
    private FragmentManager manager;
    private HomeFragment home=null;
    private FindFragment find=null;
    private MyFragment my=null;
    private SlidingMenu slidingMenu;
    private long mExitTime;
    private UMShareAPI umShareAPI;
    private ImageView header_logo;
    private DisplayImageOptions options;
    private AlertDialog dialog;
    private UpdateEntity updateEntity;

    /**
     * 消息机制
     */
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    dialog.setMessage(updateEntity.getDescription());
                    dialog.show();
                    break;

                case 1:
                    downLoadApk();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        dialog = new AlertDialog.Builder(MainActivity.this).
                setTitle("升级提醒").
                setIcon(R.mipmap.ch_tag_new).
                setPositiveButton("在线升级", onclick).
                setNegativeButton("不想升级", null).
                create();

        //开启线程
        new Thread(new CheckVersionTask()).start(); //检查版本号



        PushAgent.getInstance(this).onAppStart();//消息推送

        //初始化侧拉菜单
        initSliding();
        /**
         * 找控件
         */
        group = (RadioGroup) findViewById(R.id.footer_rg);
        header_logo = (ImageView) findViewById(R.id.header_logo);

        //获取FragmentManager对象
        manager = getSupportFragmentManager();
        //开启事务
        FragmentTransaction transaction = manager.beginTransaction();
        //加载fragment
        transaction.add(R.id.content, home=new HomeFragment(), "home");
        transaction.add(R.id.content, find=new FindFragment(), "find");
        transaction.add(R.id.content, my=new MyFragment(), "my");
        //提交事务
        transaction.commit();

        //切花页面的方法
        switchTag("home");

        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.home:
                        switchTag("home");//显示首页页面
                        break;
                    case R.id.find:
                        switchTag("find");//显示发现页面
                        break;
                    case R.id.my:
                        switchTag("my");//显示个人页面
                        break;
                }
            }
        });
    }

    DialogInterface.OnClickListener  onclick = new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.sendEmptyMessage(1);
        }

    };

    /**
     * 切换fragment页面
     * 隐藏/显示
     * 相比replace而言：页面切换更流畅
     * @param tag
     */
    private void switchTag(String tag) {
        //开启事务
        FragmentTransaction transaction = manager.beginTransaction();
        if ("home".equals(tag)){
            transaction.show(home);//显示
            transaction.hide(find);//隐藏
            transaction.hide(my);
        }else if ("find".equals(tag)){
            transaction.show(find);
            transaction.hide(home);
            transaction.hide(my);
        }else if ("my".equals(tag)){
            transaction.show(my);
            transaction.hide(find);
            transaction.hide(home);
        }
        //提交事务
        transaction.commit();
    }

    public void leftMenu(View v) {
        /*
         * showMenu();显示侧拉菜单
         * showContent();隐藏Menu菜单
         */
        slidingMenu.showMenu();//显示侧拉菜单
    }

    public void rightMenu(View v) {
        Toast.makeText(this, "暂不支持搜索功能哦", Toast.LENGTH_SHORT).show();
    }

    /*
     * 配置侧拉菜单
     */
    public void initSliding(){
        // 设置侧拉条目布局
        setBehindContentView(R.layout.layout_menu);
        // 获取侧拉栏目对象
        slidingMenu = getSlidingMenu();

        /*
         * SlidingMenu.TOUCHMODE_FULLSCREEN全屏触摸有效 SlidingMenu.TOUCHMODE_MARGIN
         * 拖拽边缘有效 SlidingMenu.TOUCHMODE_NONE 不响应触摸事件
         */
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

        // 设置内容显示页对应的dp大小
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        // //设置左侧侧拉栏目宽度
        // slidingMenu.setBehindWidth(140);
        // 设置侧拉栏目所在位置
        /*
         * SlidingMenu.LEFT SlidingMenu.LEFT_RIGHT SlidingMenu.RIGHT
         */
        slidingMenu.setMode(SlidingMenu.LEFT);
        // 给侧拉栏目和左侧内容页区分开(加线)
        slidingMenu.setShadowDrawable(R.mipmap.slide_bottom_bar);
        // 设置线的宽度
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);

        // fragment去替换布局中节点
        LeftMenuFragment menuFragment = new LeftMenuFragment();
        // FragmentManager管理者
        getSupportFragmentManager()
                // 开启事物
                .beginTransaction()
                // 通过fragment去替换对应布局
                .replace(R.id.menu_frame, menuFragment, "leftMenu")
                // 提交事物
                .commit();
    }

    /**
     * 监听返回键
     * 目的：提醒用户是否退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(slidingMenu.isMenuShowing() ||slidingMenu.isSecondaryMenuShowing()){
                slidingMenu.showContent();
            }else {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "在按一次退出程序",
                            Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();//关闭当前页面
                }
            }
            return true;
        }
        //拦截MENU按钮点击事件，让他无任何操作
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
    }

    /*
	 * 从服务器中下载APK
	 */
    protected void downLoadApk() {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file =  getFileFromServer(updateEntity.getUrl(), pd);
                    sleep(1000);

                    UpdateTools tools = new UpdateTools();
                    //安装APk
                    tools.installApk(file,MainActivity.this);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }}.start();
    }
    /*
	 * 从服务器获取xml解析并进行比对版本号
	 */
    public class CheckVersionTask implements Runnable{

        public void run() {
            try {
                //从资源文件获取服务器 地址
                String path = getResources().getString(R.string.serverurl);
                //包装成url的对象
                URL url = new URL(path);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                InputStream is =conn.getInputStream();
                updateEntity =  UpdateTools.getUpdataInfo(is);
                //当前版本号
                int versionCode = MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;

                if(Integer.parseInt(updateEntity.getVersion()) <= versionCode){
                }else{
                    handler.sendEmptyMessage(0);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 下载方法
     *
     * @param path
     * @param pd
     * @return
     * @throws Exception
     */
    public File getFileFromServer(String path, ProgressDialog pd)
            throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            String fileSize = Formatter.formatFileSize(this, conn.getContentLength());
            pd.setProgressNumberFormat(fileSize);
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(),
                    "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                String fileSizes = Formatter.formatFileSize(this, total);
                pd.setProgressNumberFormat(fileSizes);//显示apk安装包的大小
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }
}

